package com.jfire.json.field.lang;

import java.lang.reflect.Field;
import com.jfire.baseutil.collection.ObjectCollect;
import com.jfire.baseutil.collection.StringCache;
import com.jfire.json.JsonArray;
import com.jfire.json.JsonObject;
import com.jfire.json.field.JsonField;

@SuppressWarnings("restriction")
public class CharacterField extends JsonField
{
    
    public CharacterField(Field field)
    {
        super(field);
    }
    
    @Override
    protected Object getSinlgeJsonValue(Object host, ObjectCollect collect)
    {
        return String.valueOf((Character)unsafe.getObject(host, offset));
    }
    
    @Override
    public void setOneDimension(Object value, JsonArray jsonArray, ObjectCollect collect)
    {
        for (Character each : (Character[]) value)
        {
            jsonArray.add(each);
        }
    }
    
    @Override
    protected void writeToStringByOneDimension(StringCache cache, Object value, ObjectCollect collect)
    {
        cache.append('[');
        for (char each : (Character[]) value)
        {
            cache.append('"').append(each).append('"').append(',');
        }
        if (cache.isCommaLast())
        {
            cache.deleteLast();
        }
        cache.append(']');
    }
    
    @Override
    protected void singleWriteToStr(StringCache cache, Object host, ObjectCollect collect)
    {
        cache.append(jsonKey)
                .append('"').append((Character)unsafe.getObject(host, offset)).append('"').append(',');
        
    }
    
    @Override
    protected void fillSingle(JsonObject jsonObject, Object target)
    {
        String value = jsonObject.getString(name);
        if (value != null)
        {
            unsafe.putObject(target, offset, value.charAt(0));
        }
        
    }
    
    @Override
    protected Object getOneDimensionArray(JsonArray jsonArray)
    {
        char[] array = new char[jsonArray.size()];
        for (int i = 0; i < array.length; i++)
        {
            array[i] = jsonArray.getString(i).charAt(0);
        }
        return array;
    }
    
}
